import {request} from "../../util/request.js";

const url = "https://w7de.kuyuan.vip/app/index.php?i=2&c=entry&do=cloud&m=kuyuan_check";
const wx_appid = window.sysinfo.account.key;
const timestamp = parseInt(new Date().getTime()/1000);
const module_name = "kuyuan_red_single";
let identity = "";  //验证码
let authority = "";  //授权码

/**
 * 获取云服务信息
 * @param module 模块标识
 */
let getCloud = function(){
    return new Promise((success)=>{
        request("cloud/getCloud",{
            module:module_name,
            wx_appid
        })
            .then((res)=>{
                if(res.data.status === "success"){
                    success(res.data.data);
                }
            });
    });
}

/**
 * 获取远程云服务信息
 */
let getRemoteCloud = function(identity,authority){
    return new Promise((success)=>{
        request("cloud/checkCloud",{
            identity,
            module:module_name,
            authority
        },url)
            .then((res)=>{
                if(res.data.status === "success"){
                    success(res.data.data);
                }
            });
    });
}

/**
 * 设置本地授权码信息
 */
let setLocalCloud = function(identity,data){
    return new Promise((success)=>{
        request("cloud/setAuthority",{
            identity,
            authority:data.authority,
            past_time:data.past_time,
            check_time:timestamp + 86400
        })
            .then((res)=>{
                if(res.data.status === "success"){
                    success();
                }
            });
    });
}

/**
 * 更新授权
 */
const update = function(){
    getCloud()
        .then((data)=>{
            identity = data.identity;
            authority = data.authority;
            if(timestamp > parseInt(data.check_time)){
                if(data.authority !== "" && timestamp < parseInt(data.past_time)){
                        return getRemoteCloud(identity,authority);
                }
            }
        })
        .then((res)=>{
            if(res){
                return setLocalCloud(identity,res);
            }
        })
}

/**
 * 验证授权是否设置或者已过期
 */
const check = function(){
    return new Promise((success)=>{
        getCloud()
            .then((data)=>{
                if(data.authority && timestamp < parseInt(data.past_time)){
                    success(true);
                }else{
                    success(false);
                }
            });
        });
}


export {update,check};